/**
* Created by QiYuBu on 2016/12/2.
* @ Description:[一句话描述功能]
*/
<!--非员工搜索-->
<style scoped>
  .peopleB {
    background-color: #fff;
    margin-top: .25rem;
  }
  .name-tip {
    font-size: .65rem;
    color: red;
  }

  .peopleItem {
    width: 100%;
    padding: .5rem;
    font-size: .75rem;
  }
</style>

<!--时间插件-->
<style scoped>
  .dateInput {
    position: relative;
  }

  .dateInput .dateBtn {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    height: 2.7rem;
    z-index: 3;
  }

  .dateInput .mint-button {
    height: 2.7rem;
    padding: 0;
    opacity: 0;
  }

</style>

<!--修改插件样式-->
<style>
  .picker-toolbar {
    height:2rem;
  }

  .mint-datetime-action {
    font-size: .6rem;
  }

  .mint-datetime-cancel, .mint-datetime-confirm {
    line-height: 2rem;
    font-size: .9rem;
  }

  .picker-item.picker-selected {
    color: #0094db;
  }

  .picker-item {
    font-size: .6rem;
  }
</style>
<style lang="scss" rel="stylesheet/scss" scoped>
  .page {
    height: 100%;
    background-color: #f0f0f0;
    box-sizing: border-box;
    padding: 2.2rem 0 0 0;
    .popItem {
      line-height: 2.5rem;
      width: 100%;
      border-bottom: 1px solid #ddd;
      font-size: .75rem;
      box-sizing: border-box;
      padding: 0 1.2rem;
    }
    .icon-duihao {
      font-size: .9rem;
    }
  }

  .label {
    position: relative;
    width: 100%;
    height: auto;
    font-size: .7rem;
    background-color: white;
    border-bottom: 1px solid #ddd;
    &>div {
      width: 92%;
      padding:2% 4%;
      &>* {
        line-height: 2.6em;
      }
    }
    .input {
      width: 100%;
      font-size: .75rem;
      border: none;
      height: auto;
    }
    i {
      position: absolute;
      z-index: 1;
      right: .5rem;
      font-size: .7rem;
      color: #0094db;
      height:  2.65rem;
      line-height:  2.65rem;
    }
  }
  .activePop {
    color: #0994db;
  }
</style>
<style lang="scss" rel="stylesheet/scss" scoped>
  .icon-llmainpageback {
    color: white;
    font-size: .9rem;
    line-height: 2.2rem;
  }
  .toastError {
    width: 12rem;
    text-align: center;
    .mint-toast-text {
      font-size: .7rem !important;
    }
  }
</style>
<template>
  <div class="page" @click="searchPeople=true">
    <head-nav @headBack="goback" :centerTitle="passengerTitle" rightTitle="完成" @rightClick="addPassenger(newPassengerAjax)"></head-nav>
    <div class="label">
      <div>
        <span class="labelT">姓名</span>
        <input type="text" placeholder="请输入姓名" class="input" v-model.trim="newPassenger.name" @input="change($event)">
        <span class="name-tip" v-show="nameTipsShow">在管理员确认之前，该员工资料将暂记为[待审核]状态</span>
      </div>
    </div>
    <div v-show="searchPeople">
      <div class="label" @click="sexShow = true" v-show="birthdayShow">
       <div>
         <span class="labelT">性别</span>
         <p class="input">{{newPassenger.sex}}</p>
         <i class="iconfont icon-enter"></i>
       </div>
      </div>
      <div class="label" @click="cardShow = true">
        <div>
          <span class="labelT">证件类型</span>
          <p class="input">{{newPassenger.credentialName}}</p>
          <i class="iconfont icon-enter"></i>
        </div>
      </div>

      <div class="label">
        <div>
          <span class="labelT" :class="{error:IDError}">证件号码</span>
          <input type="text" placeholder="请填写证件号码" class="input" v-model.trim="newPassenger.credentialNo">
        </div>
      </div>
      <div class="label dateInput" @click="openBirthTime" v-show="birthdayShow">
        <div>
          <span class="labelT">出生日期</span>
          <input type="text" placeholder="请选择时间" class="input" v-model.trim="handleBirthday" readonly/>
        </div>
      </div>
      <div class="label" >
        <div>
          <span class="labelT" :class="{error:IDError}">手机号码</span>
          <input type="text" placeholder="请填写手机号码" class="input" v-model.trim="newPassenger.mobile">
        </div>
      </div>
    </div>
    <!--选择证件-->
    <popup v-model="cardShow" position="bottom" style="width: 100%">
      <div v-for="(pop,index) in credentialInfo" class="popItem" :class="{activePop:pop.isSelected}"
           @click="popActive(index,1)">
        {{pop.itemTxt}}<i class="iconfont icon-duihao fr" v-show="pop.isSelected"></i>
      </div>
    </popup>
    <!--选择性别-->
    <popup v-model="sexShow" position="bottom" style="width: 100%">
      <div v-for="(pop,index) in sexInfo" class="popItem" :class="{activePop:pop.isSelected}"
           @click="popActive(index,2)">
        {{pop.name}}<i class="iconfont icon-duihao fr" v-show="pop.isSelected"></i>
      </div>
    </popup>
  </div>
</template>
<script type="text/ecmascript-6">
  import { Popup, DatetimePicker, Toast, Indicator } from 'mint-ui';
  import {HeadNav} from 'wxm-common';
  export default {
    components: {[DatetimePicker.name]: DatetimePicker,HeadNav,Popup},
    data () {
      return {
        nameTipsShow: false,
        mindate: new Date('1970-01-01'),
        maxdate: new Date(),
        pickerVisible: null,
        startTime: '',
        from: '',
        birthdayShow: false,
        olddate: null,
        searchPeople: true,
        pageList: [
          {
            fullname: '张三',
          },
          {
            fullname: '张四',
          },
          {
            fullname: '张五'
          },
        ],
        visible2: false,
        dateValue: '',
        sexShow: false,
        cardShow: false,
        mode: 'ADD',
        IDError: false,
        newPassenger: {
          userId: null,
          costUnitCode: 'cost',//成本中心code
          orgId: '11', //组织id
          corporationId: 'corpId',//法人id
          amount: null,//分摊金额 ,暂时为票单价金额  -后台计算
          mobile: '', // 手机(可为空)
          email: '',// 邮箱(可为空)
          travelCode: '',//差旅类型code(可为空)
          empLevelCode: '',//职级code(可为空)
          isPassEmpLevel: false,//是否通过审核的职级(可为空)
          travellerType: '1',
          birthday: '',
          name: '',
          sex: '男',
          sexType: 'M',
          credentialName: '身份证',
          credentialType: 'IDENTITY',
          passengerType: 'ADU', /*把所有的新增乘机人都当成成人类型*/
          credentialNo: '',
          checked: true,
        },
        centerTitle: '新增乘客',
        rightTitle: '完成',
        sexInfo: [{
          name: '男',
          type: 'M',
          isSelected: true,
        }, {
          name: '女',
          type: 'F',
          isSelected: false,
        }

        ]
      }
    },
    methods: {
      //控制修改姓名后提示语显示
      change(e) {
        //travellerType = 3 员工
        var passenger = this.$store.state.passengers;
        if(this.mode == 'UPDATE') {
          var that = this,
              index = this.$route.query.index;
          that.value = e.target.value;
          if(passenger[index].travellerType == 3) {
            if(that.$store.state.passengers[index].name !== that.value) {
              that.nameTipsShow = true;
            } else {
              that.nameTipsShow = false;
            }
          }
        }
      },
      openBirthTime() {
          var that = this;
          that.$vux.datetime.show({
            cancelText: '取消',
            confirmText: '确定',
            startDate: '1950-01-01',
            endDate: that.formatDate(new Date()),
            onConfirm(val) {
              that.newPassenger.birthday = val;
            },
            onCancel() {
            }
          })
      },
      openPicker() {
        this.$refs.picker.open();
      },
      formatDate(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? '0' + m : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        return y + '-' + m + '-' + d;
      },
      popActive (index, type) {
        switch (type) {
          case 1:
            for (var i = 0; i < this.credentialInfo.length; i++) {
              this.$store.state.credentialInfo[i].isSelected = false
            }
            var itemIndex = this.$route.query.index; //当前乘客中修改的第几个
            var that = this;
            if(itemIndex + 1) {
             var currentId = this.$store.state.passengers[itemIndex].userId, //判断这个乘客的userID是否和登陆人id一致
                loginId = this.$store.state.userInfo.userId,
                userCardInfo = this.$store.state.userInfo.cardType; //当前登录人所有的证件信息数据
              if(currentId == loginId) {
                //循环当前登陆人的证件信息数组，赋值
                var tmp = null;
                $.each(userCardInfo, function (i, item) {
                  //有对于的证件信息就全部带过来，没有的话则清空对于的证件号码
                  if(item.idType == that.credentialInfo[index].itemCode) {
                    tmp = i;
                    that.newPassenger.credentialNo = userCardInfo[tmp].idNumber;
                    //that.newPassenger.birthday = userCardInfo[tmp].validDate;
                    return false;
                  } else {
                    that.newPassenger.credentialNo = '';
                  }
                })
              } else {
                //如果不是当前登陆人，目前只做切换证件时候清空证件数据，保留当前证件数据
                var curCardType = that.passengers[index].credentialType
                var togCardType = that.credentialInfo[index].itemCode;
                var curNo = that.$store.state.passengers[itemIndex].credentialNo;
                if(curCardType == togCardType) {
                  that.newPassenger.credentialNo = curNo;
                } else {
                  that.newPassenger.credentialNo = '';
                }
              }
            }
            that.$store.state.credentialInfo[index].isSelected = true
            that.cardShow = false
            that.newPassenger.credentialType = that.credentialInfo[index].itemCode
            that.newPassenger.credentialName = that.credentialInfo[index].itemTxt

            if (index == 0) {
              that.birthdayShow = false  //控制出生日期显示隐藏
              break
            } else {
              that.birthdayShow = true  //控制出生日期显示隐藏
              that.dateShow = false
            }
            break
          case 2:
            for (var k = 0; k < this.sexInfo.length; k++) {
              this.sexInfo[k].isSelected = false
            }
            this.sexInfo[index].isSelected = true
            this.sexShow = false
            this.newPassenger.sex = this.sexInfo[index].name
            this.newPassenger.sexType = this.sexInfo[index].type
            break
        }

      },
      goback () {
        this.$router.go(-1)
      },
      submit (newPassengerAjax) {
        Indicator.open({
          text: '加载中...',
          spinnerType: 'fading-circle'
        })
        var that = this
        var id = this.newPassenger.credentialNo
        var type = this.newPassenger.credentialType
        var name = this.newPassenger.name
        //判断是那个过来的
        let toname = this.$route.query.state
        if (type === 'IDENTITY') {
          var str = this.checkID(id)
          if (str === 'pass') {
            var serverUrl = $tool.getServerUrl();
            $.ajax({
              url: serverUrl + '/members/traveller/saveOrUpdate.json',
              type: 'get',
              traditional: true,
              data: newPassengerAjax,
              dataType: 'jsonp',
              jsonp: 'callback',
              jsonpCallback: 'callback',
            }).done(function (res) {
              Indicator.close()
              if (toname == 'plan') {
                that.$store.state.traveldata.usurdata.push(that.newPassenger)
                that.$router.go(-1)
              } else {
                if (that.mode == 'ADD') {
                  that.$store.commit('ADD_PASSENGER', that.newPassenger)
                } else {
                  var index = that.$route.query.index
                  that.$store.state.passengers[index] = that.newPassenger
                }
                that.$router.go(-1)
              }
            }).fail(function (res) {
              Indicator.close()
            })
          } else {
            that.IDError = true
            that.$vux.toast.show({
              type: 'text',
              text: '身份证填写错误',
              time: 1000
            })
          }
        } else {
          var serverUrl = $tool.getServerUrl();
          $.ajax({
            url: serverUrl + '/members/traveller/saveOrUpdate.json',
            type: 'get',
            traditional: true,
            data: newPassengerAjax,
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'callback',
          }).done(function (res) {
            Indicator.close()
            if (toname == 'plan') {
              that.$store.state.traveldata.usurdata.push(that.newPassenger)
              that.$router.go(-1)
            } else {
              if (that.mode == 'ADD') {
                that.$store.commit('ADD_PASSENGER', that.newPassenger)
              } else {
                var index = that.$route.query.index
                that.$store.state.passengers[index] = that.newPassenger
              }
              that.$router.go(-1)
            }
          }).fail(function (res) {
            Indicator.close()
          })
        }

      },
      addPassenger (newPassengerAjax) {
        var index = this.$route.query.index;
        for (var i = 0; i < this.passengers.length; i++) {
          if(i == index){
            continue;
          }
          if (this.newPassenger.credentialNo == this.passengers[i].credentialNo) {
            this.$vux.toast.show({
              type: 'text',
              text: '近期乘客中,该证件号已被使用',
              time: 1000
            })
            return;
          }

          if (this.newPassenger.name == this.passengers[i].name) {
            this.$vux.toast.show({
              type: 'text',
              text: '请勿重复添加乘客',
              time: 1000
            })
            return
          }
        }

        var isName = this.newPassenger.name.checkFlightName()
        var isNameFlight = this.newPassenger.name.checkFlightName()

//        if (isName == false && this.from == 'trainBooking') {
//          this.$vux.toast.show({
//            type: 'text',
//            text: '请使用简体中文或英文填写姓名',
//            time: 1000
//          })
//          return
//        }
    if(this.newPassenger.mobile) {
        if(!/^[1][3,4,5,7,8][0-9]{9}$/.test(this.newPassenger.mobile)) {
          this.$vux.toast.show({
            type: 'text',
            text: '手机号码输入错误',
            time: 1000
          })
          return
        }
    }
     if (!isNameFlight && (this.from == 'booking' || this.from == 'returnbooking')) {
          this.$vux.toast.show({
            type: 'text',
            text: '姓名格式不正确',
            time: 1000
          })
          return
        }
        else if (this.newPassenger.credentialNo == '') {
          this.$vux.toast.show({
            type: 'text',
            text: '请填写证件号码',
            time: 1000
          })
          return
        }
        else if (this.newPassenger.credentialName != '身份证' && (this.newPassenger.birthday == '' || this.newPassenger.birthday == undefined)) {
          this.$vux.toast.show({
            type: 'text',
            text: '请选择出生日期',
            time: 1000
          })
          return
        }
        else if (this.newPassenger.credentialNo != '' && this.newPassenger.credentialName == '身份证') {
          var result = this.checkID(this.newPassenger.credentialNo)
          if (result == 'pass') {
            this.submit(newPassengerAjax)
          } else {
            this.$vux.toast.show({
              type: 'text',
              text: '身份证填写错误',
              time: 1000
            })
          }
        } else {
          this.submit(newPassengerAjax)
        }
    },
    checkID (ID) {
      if (typeof ID !== 'string') return '非法字符串'
      var city = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江 ',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北 ',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏 ',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '新疆',
        71: '台湾',
        81: '香港',
        82: '澳门',
        91: '国外'
      }
      var birthday = ID.substr(6, 4) + '/' + Number(ID.substr(10, 2)) + '/' + Number(ID.substr(12, 2))
      var d = new Date(birthday)
      var newBirthday = d.getFullYear() + '/' + Number(d.getMonth() + 1) + '/' + Number(d.getDate())
      var currentTime = new Date().getTime()
      var time = d.getTime()
      var arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      var arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
      var sum = 0, i, residue

      if (!/^\d{17}(\d|x)$/i.test(ID)) return '非法身份证'
      if (city[ID.substr(0, 2)] === undefined) return '非法地区'
      if (time >= currentTime || birthday !== newBirthday) return '非法生日'
      for (i = 0; i < 17; i++) {
        sum += ID.substr(i, 1) * arrInt[i]
      }
      residue = arrCh[sum % 11]
      if (residue !== ID.substr(17, 1)) return '非法身份证哦'

      //    return city[ID.substr(0,2)]+","+birthday+","+(ID.substr(16,1)%2?" 男":"女")
      return 'pass'
    },
    isChinaOrLett (name) {
//            var regu = "^[a-zA-Z\u4e00-\u9fa5\s/]+$";
      var regu = /^(?=[\a-zA-Z\s\/]{6,26}$)/
      var regu1 = /^(?=[\u4e00-\u9fa5]{2,11}$)/
      var re = new RegExp(regu)
      var re1 = new RegExp(regu1)
      if (name.length === 0) {
        return false
      } else if (re1.test(name) || re.test(name)) {
        return true
      } else {
        return false
      }
    },
  }
  ,
  computed: {
    /* minYear(){
       return new Date(new Date().getFullYear() - 100, 0, 1);
     },*/
    handleBirthday () {
      return moment(this.newPassenger.birthday).format('YYYY-MM-DD') == 'Invalid date' ? '' : moment(this.newPassenger.birthday).format('YYYY-MM-DD')
    },
    startDate()
    {
      return new Date(new Date().getFullYear() - 100, 0, 1)
    }
  ,
    newPassengerAjax()
    {
      var newPassengerAjax = {}
      newPassengerAjax.fullname = this.newPassenger.name//名字
      newPassengerAjax.gender = this.newPassenger.sexType//性别
      newPassengerAjax.idType = this.newPassenger.credentialType//证件类型
      newPassengerAjax.idNumber = this.newPassenger.credentialNo//证件号
      newPassengerAjax.birthday = this.newPassenger.birthday//出身日期
      newPassengerAjax.mobile = this.newPassenger.mobile//出身日期
      return newPassengerAjax
    }
  ,
    passengerAll()
    {
      return this.$store.state.passengers
    }
  ,
    passengers()
    {

      return this.$store.state.passengers
    }
  ,
    passengerSelected()
    {
      return this.$store.state.passengers.filter(todo => todo.checked)
    }
  ,
    credentialInfo()
    {
      var arr = this.$store.state.credentialInfo
      for (var i = 1; i < arr.length; i++) {
        arr[i].isSelected = false
      }
      arr[0].isSelected = true
      return this.$store.state.credentialInfo
    }
  ,
    passengerTitle()
    {
      return this.mode == 'ADD' ? '新增乘客' : '更新乘客'
    }
  }
  ,
  mounted()
  {
    var index = this.$route.query.index
    var passengers = this.$store.state.passengers
    if (index > -1 && index < passengers.length) {
      this.mode = 'UPDATE';
      // $.extend(this.newPassenger, passengers[index])
      Object.assign(this.newPassenger, passengers[index]);
      if(passengers[index].credentialType === 'IDENTITY') {
        this.birthdayShow = false;
      } else {
        this.birthdayShow = true;
      }
      //对应的证件类型初始化要选中状态
      var cur = null;
      for (var i = 0; i < this.credentialInfo.length; i++) {
        this.$store.state.credentialInfo[i].isSelected = false
        if(this.$store.state.credentialInfo[i].itemCode ==  passengers[index].credentialType) {
          cur = i;
        }
      }
      this.$store.state.credentialInfo[cur].isSelected = true
      //对应的性别类型初始化也要选中状态
      var xIndex = null;
      $.each(this.sexInfo, function (x, item) {
        if(item.name == passengers[index].sex) {
          xIndex = x;
          return false;
        }
      })
      for (var k = 0; k < this.sexInfo.length; k++) {
        this.sexInfo[k].isSelected = false
      }
      this.sexInfo[xIndex].isSelected = true
    }

  },
  watch: {
    "newPassenger.name" (curVal,oldVal) {
      let re = /^[\u4e00-\u9fa5]{0,}$/;
      if (re.test(this.newPassenger.name)) {
        if (curVal.length > 15) {
          this.newPassenger.name = oldVal
          this.$vux.toast.show({
            time: 1000,
            type: 'warn',
            text: '中文姓名字符不得超过15个',
            position: 'middle'
          })
        }
      } else {
        if (curVal.length > 30) {
          this.newPassenger.name = oldVal
          this.$vux.toast.show({
            time: 1000,
            type: 'warn',
            text: '英文姓名字符不得超过30个',
            position: 'middle'
          })
        }
      }
    }
  },
  beforeRouteEnter(to, from, next)
  {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不！能！获取组件实例 `this`
    // 因为当钩子执行前，组件实例还没被创建
    next(vm => {
      vm.from = from.name
    })
  }
  ,
  }
</script>
